package cn.itcast.bos.web.action;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.google.common.base.Strings;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.domain.base.Courier;
import cn.itcast.bos.domain.base.Standard;
import cn.itcast.bos.service.CourierService;
import cn.itcast.bos.web.action.common.BaseAction;

@ParentPackage("json-default")
@Namespace("/")
@Scope("prototype")
@Controller
public class CourierAction extends BaseAction<Courier> {

	private static final long serialVersionUID = 1L;

	@Autowired
	private CourierService courierService;
	// 保存快递员信息
	@Action(value = "courier_save", results = {
			@Result(name = "success", location = "./pages/base/courier.html", type = "redirect"),
			@Result(name="error",type="redirect",location="unauthorized.html")})
	public String save() {
		try {
			courierService.save(model);
			return SUCCESS;
		} catch (Exception e) {
			//e.printStackTrace();
			return ERROR;
		}
		
	}
	
	// 删除快递员信息
	//属性驱动获取id
	private String ids;
	public void setIds(String ids) {
		this.ids = ids;
	}

	@Action(value = "courier_delBatch", results = {
			@Result(name = "success", location = "./pages/base/courier.html", type = "redirect") })
	public String delBatch() {
		//将传递过来的id字符串，分割成id字符串数组
		String[] idArr = ids.split(",");
		courierService.deleteCourier(idArr);
		return SUCCESS;
	}
	
	//还原快递员信息
	@Action(value = "courier_backBatch", results = {
			@Result(name = "success", location = "./pages/base/courier.html", type = "redirect") })
	public String backBatch() {
		//将传递过来的id字符串，分割成id字符串数组
		String[] idArr = ids.split(",");
		courierService.backCourier(idArr);
		return SUCCESS;
	}
	
	// 快递员条件分页查询

	@Action(value = "courier_pageQuery", results = { @Result(name = "success", type = "json") })
	public String pageQuery() {
		Pageable pageable = new PageRequest(page - 1, rows);
		// Page<Courier> pageData = courierService.findPageDate(pageable);
		// Map<String,Object> map = new HashMap<String,Object>();
		// map.put("total", pageData.getTotalElements());
		// map.put("rows", pageData.getContent());
		// ServletActionContext.getContext().getValueStack().push(map);

		// 定义specification
		Specification<Courier> specification = new Specification<Courier>() {

			@Override
			public Predicate toPredicate(Root<Courier> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				Predicate predicate = null;
				// 定义list用来封装多个查询条件
				List<Predicate> list = new ArrayList<Predicate>();
				// 快递员工号
				if (StringUtils.isNotBlank(model.getCourierNum())) {
					Predicate p = cb.equal(root.get("courierNum").as(String.class), model.getCourierNum());
					list.add(p);
				}
				// 所属单位
				if (StringUtils.isNotBlank(model.getCompany())) {
					Predicate p = cb.like(root.get("company").as(String.class), "%" + model.getCompany() + "%");
					list.add(p);
				}

				// 取派员类型
				if (StringUtils.isNotBlank(model.getType())) {
					Predicate p = cb.like(root.get("type").as(String.class), "%" + model.getType() + "%");
					list.add(p);
				}

				// 收派标准名称(多表)
				// 指定连接
				Join<Courier, Standard> join = root.join("standard", JoinType.INNER);
				if (model.getStandard() != null && model.getStandard().getId()!=null) {
					Predicate p = cb.equal(join.get("id").as(Integer.class), model.getStandard().getId());
					list.add(p);
				}

				// 构建条件组合
				if (list != null && list.size() >= 0) {
					Predicate[] pArr = new Predicate[list.size()];
					predicate = cb.and(list.toArray(pArr));
				}
				return predicate;
			}
		};
		Page<Courier> pageData = courierService.findPageDate(specification, pageable);

		pushPageDataToValueStack(pageData);
		
		return SUCCESS;
	}
	
	//查询没有关联定区的快递员
	@Action(value="courier_findnoassociation",results={@Result(name="success",type="json")})
	public String findnoassociation() {
		//调用业务层查询未关联定区的快递员
		List<Courier> list = courierService.findnoassociation();
		ServletActionContext.getContext().getValueStack().push(list);
		return SUCCESS;
	}
	
	//根据定区id查询关联的快递员
	//属性驱动获取定区id
	private String fixedAreaId;
	public void setFixedAreaId(String fixedAreaId) {
		this.fixedAreaId = fixedAreaId;
	}

	@Action(value="courier_findAssociationCourier",results={@Result(name="success",type="json")})
	public String findAssociationCourier() {
		List<Courier> list = courierService.findAssociationCourier(fixedAreaId);
		ServletActionContext.getContext().getValueStack().push(list);
		return SUCCESS;
	}

}
